const jwt = require('jsonwebtoken');
const JWT_SECRET = '1024lab__1024lab'; // 确保保密

// Token 验证中间件
exports.verifyToken = (req, res, next) => {
    const token = req.headers['authorization']; // 从请求头中获取 Token
    if (!token) {
        return res.status(403).cc({message: '无权访问'});
    }

    jwt.verify(token, JWT_SECRET, (err, decoded) => {
        if (err) {
            return res.status(401).cc({message: '无效的 Token'});
        }
        req.user = decoded; // 将解码后的用户信息放入请求对象
        next(); // 继续处理请求
    });
}
exports.generateToken = (user, loginDevice) => {
    return jwt.sign(
        {
            id: user.id, username: user.loginName,
            device: loginDevice
        }, JWT_SECRET,
        {expiresIn: '1h'});
}